package com.sam.im.heiqun.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import com.google.gson.Gson;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.ImMessageData;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.uis.activities.ChatActivity;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.UUID;

import io.socket.client.Ack;
import io.socket.client.Socket;

/**
 * http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
 */
public class ConversationUtils {

    public long destid = 0;
    public String fromid;
    private UserEntivity userEntivity;
    private static Socket mSocket;
    private Context mContext;
    private Gson gson;

    public ConversationUtils(Context context) {
        mContext = context;
        userEntivity = ToolsUtils.getUser();
        fromid = ToolsUtils.getMyUserId();
        gson = new Gson();
    }

    /**
     * 发送开视频消息
     */
    public void sendMsg(String msgjson, int typecode, int destid) {
        if (msgjson == null || msgjson.equals("")) {
            return;
        }
        setSocket();
        //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
        String uuid = "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis();
        Log.i("wgdinfo", "sendMsg: ----头像头像头像--------userEntivity.getHeadUrl()=" + userEntivity.getHeadUrl());
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, typecode, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, msgjson, typecode,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        socketSend(imMessage, null, 0, 0);

        try {
            MsgEntity msgEntity = new Gson().fromJson(msgjson, MsgEntity.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void sendMsgTime(String msgjson, int typecode, int destid) {//send_type 1挂断

        if (msgjson == null || msgjson.equals("")) {
            return;
        }
        setSocket();
        //这里UUID与iOS联通，UUID作为唯一标识，所以本地拼接，规则：聊天类型（单聊是1，群聊是2）+“-”+目标id+“-”+我的id+“-”+时间戳；
        String uuid = "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis();
        Log.i("wgdinfo", "sendMsg: ----头像头像头像--------userEntivity.getHeadUrl()=" + userEntivity.getHeadUrl());
        final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, typecode, UUID.randomUUID().toString(), Long.parseLong(fromid), Constant.FROM_TYPE_MAM, destid, msgjson, Constant.MESSAGE_TYPR_BQEMOJI,
                System.currentTimeMillis(), System.currentTimeMillis(), 0, null, fromid + "_" + destid, 0, userEntivity.getHeadUrl());
        imMessage.setSendState(Constant.COMPLETED);
        /*tblist.add(imMessage);
        sendMessageHandler.sendEmptyMessage(SEND_OK);*/
        socketSend(imMessage, null, 0, 0);
        MessageEntivity messageEntivity = IMMessageToJson.ImMessageToMessageEntivity(imMessage, com.sam.im.heiqun.constant.Constant.FROM_TYPE_OTHER);
        imMessage.save();//存储接受的数据
        if (ChatActivity.isLive) {
            Log.i("-----", "sendMsgTime: ========001=======");
            EventBus.getDefault().post(new ImMessageData(imMessage));
        } else {
            Log.i("-----", "sendMsgTime: ========002=======");
            EventBus.getDefault().post(messageEntivity);
        }

        try {
            MsgEntity msgEntity = new Gson().fromJson(msgjson, MsgEntity.class);
            //openklRed(msgEntity.getMsgString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setSocket() {
        mSocket = App.socket;
        if (mSocket == null || !mSocket.connected()) {//mSocket 为空  这个基本不会出现 、或者链接断开了
            EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
            String savesocketstr = ToolsUtils.savesocketstr(mContext, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
            // App.initSocket(App.imIpAfterReady, App.tokenAfterReady);
        }
    }


    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub, final String address, final double lat, final double lut) {

        new Thread(new Runnable() {
            boolean sendState = false;
            int retryCount = 0;

            @Override
            public void run() {
//                if (tbub.getMessageType() != Constant.MESSAGE_TYPR_READ) {//已读
//                    tbub.save();
//                    ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
//                    IMMessageToJson.ImMessageToMessageEntivity(imMessage, Constant.FROM_TYPE_SELF);
//                    socketSend(imMessage);
//                } else {
                socketSend(tbub);
//                }
            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            private void socketSend(final ImMessage imMessage) {
                while (!sendState && retryCount < 2) {
                    if (retryCount == 1) {
                        imMessage.setSendState(Constant.SENDERROR);
                        if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
//                            imMessage.save();
                        }
                        tbub.setSendState(Constant.SENDERROR);
                        return;
                    }
                    try {//这里不能报异常
                        //imMessage.getType() == ChatRecyclerAdapter.TO_USER_IMG |
                        if (imMessage.getType() == ChatRecyclerAdapter.TO_USER_READDELETE | imMessage.getMessageType() == ChatRecyclerAdapter.TO_USER_IMG && !imMessage.getContent().contains("http"))//图片
                        {
                            if (imMessage.getFilePath() != null && imMessage.getFilePath().contains("storage") | imMessage.getFilePath().contains("sdcard")) {
                                String response = HttpAssist.uploadFile(new File(imMessage.getFilePath()), "", false);//上传图片
                                ImageEntity imageEntity = gson.fromJson(response, ImageEntity.class);
                                String url = imageEntity.getData().getInfo().get(0);
                                imMessage.setContent(url);
                                imMessage.setFileUrl(url);
                                tbub.setContent(url);
                                tbub.setFileUrl(url);
                            }
                        }
                    } catch (Exception e) {
                        //没有网络时获取到的数据是错误的，不能使用gson转换
                        e.printStackTrace();
                    }
                    mSocket = App.socket;
                    retryCount++;


                    if (mSocket != null) {
//                        imMessage.setSendState(Constant.COMPLETED);
//                        final ImMessage  mmimMessage1 = imMessage;
                        Log.i("info", "发送的图片路径：" + imMessage.getContent());
                        mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                            @Override
                            public void call(Object... args) {
                                String message = args[0].toString();
                                ImMessage ss = IMMessageToJson.jsonToImMessage(message);
//                                Log.i("info", "发送的图片路径===" + imMessage.getContent() + "\n" + ss);
                                imMessage.setSendState(Constant.COMPLETED);
                                tbub.setSendState(Constant.COMPLETED);
                                if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
//                                imMessage.save();
                                }
//                                mmimMessage1.setSendState(Constant.COMPLETED);
//                                tbub.setSendState(Constant.COMPLETED);
//                                if (mmimMessage1.getMessageType() != Constant.MESSAGE_TYPR_READ) {
//                                    mmimMessage1.save();
//                                }

                                sendState = true;
                            }
                        });
                    }
                    try {
                        Thread.sleep(Constant.SOCKET_SEND_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

}
